package cn.gbase.jiangsu.data.transfer.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Company;
import cn.gbase.jiangsu.data.transfer.bean.ForumReply;
import cn.gbase.jiangsu.data.transfer.bean.ForumTopic;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.common.Constants;

/**
 * 论坛管理功能（运营商与服务站之间）.
 * 
 */
@IocBean(args = { "refer:dao" })
public class ForumS2OService extends IdEntityService<ForumTopic> {
	@Inject
	private SupplierService supplierService;
	@Inject
	private CompanyService companyService;
	/**
	 * 缓存供货商的名称.
	 */
	private static Map<Integer, String> supplierNameMap = new HashMap<Integer, String>();

	/**
	 * 缓存供货商的名称.
	 */
	private static Map<Integer, String> companyNameMap = new HashMap<Integer, String>();

	public ForumS2OService() {
		super();
	}

	public ForumS2OService(Dao dao) {
		super(dao);
	}

	/**
	 * 根据ID取得主题.
	 * 
	 * @param TopicId
	 * @return
	 */
	public ForumTopic getTopic(int TopicId) {
		ForumTopic topic = this.dao().fetch(ForumTopic.class, TopicId);
		if (topic != null) {
			if (topic.getFromType().equals("O")) {
				topic.setFromName("运营商");
				topic.setToName(this.getSupplierName(topic.getToId()));
			} else {
				topic.setFromName(this.getSupplierName(topic.getFromId()));
				topic.setToName("运营商");
			}
		}
		return topic;
	}

	/**
	 * 取得供货商的名称.
	 * 
	 * @param supplierId
	 *            供货商ID
	 * @return
	 */
	private String getSupplierName(Integer supplierId) {

		// 先从缓存取
		if (supplierNameMap.containsKey(supplierId)) {
			return supplierNameMap.get(supplierId);
		}

		// 再从DB取
		Supplier s = supplierService.getSupplier(supplierId);
		if (s == null) {
			supplierNameMap.put(supplierId, "");
			return "";
		}
		supplierNameMap.put(supplierId, s.getSupplierName());
		return s.getSupplierName();
	}
	
	/**
	 * 取得主题列表.
	 * 
	 * @param pageNumber
	 * @param name
	 * @return
	 */
	public QueryResult getTopicList(int pageNumber, int companyId, String title) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("deleteFlag", "=", 0);
		if (title != null && title.length() > 0) {
			group = group.and("topicTitle", "like", "%" + title + "%");
		}

		// 版面1是运营商与服务站之间的帖子
		group = group.and("forumId", "=", Constants.FORUM_ID_O2S);

		// 发帖人ID或收贴人ID是指定的服务站
		SqlExpressionGroup group2 = null;
		if (companyId > 0) {
			group2 = Cnd.exps("fromType", "=", "S").and("fromId", "=",
					companyId);
			group2 = group2.or("toType", "=", "S").and("toId", "=", companyId);
			group2 = group2.or("fromType", "=", "O").and("toId", "=", 0);
			
			group = group.and(group2); // 两组条件and在一起。
		}

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber,
				Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(ForumTopic.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<ForumTopic>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<ForumTopic> resultList = this.dao().query(ForumTopic.class,
				Cnd.where(group).desc("topicId"), pager); // 当前页面显示记录

		// 取得发帖人/收贴人的名称
		for (ForumTopic topic : resultList) {
			if (topic.getFromType().equals("O")) {
				topic.setFromName("运营商");
				topic.setToName(this.getSupplierName(topic.getToId()));
			} else {
				topic.setFromName(this.getSupplierName(topic.getFromId()));
				topic.setToName("运营商");
			}
		}

		// 返回
		return new QueryResult(resultList, pager);
	}

	/**
	 * 取得服务站的名称.
	 * 
	 * @param companyId
	 *            服务站ID
	 * @return
	 */
	private String getCompanyName(Integer companyId) {

		// 先从缓存取
		if (companyNameMap.containsKey(companyId)) {
			return companyNameMap.get(companyId);
		}

		// 再从DB取
		Company c = companyService.getCompany(companyId);
		if (c == null) {
			companyNameMap.put(companyId, "");
			return "";
		}
		companyNameMap.put(companyId, c.getCompanyName());
		return c.getCompanyName();
	}

	/**
	 * 取得前n个主题列表.
	 * 
	 * @return
	 */
	public List<ForumTopic> getTopTopicList(int topSize) {
		Pager pager = this.dao().createPager(1, topSize);

		return this.dao().query(ForumTopic.class, Cnd.orderBy().asc("topicId"),
				pager);
	}

	/**
	 * 添加或更新主题.
	 * 
	 * @param Topic
	 * @return
	 */
	public boolean addOrUpdTopic(ForumTopic topic,int companyId) {
		if (topic.getTopicId() == null) {
			return addTopic(topic,companyId);
		}
		return updateTopic(topic,companyId);
	}

	/**
	 * 添加主题.
	 * 
	 * @param Topic
	 * @return
	 */
	public boolean addTopic(ForumTopic topic,int companyId) {

		// 设置字段
		Date now = new Date();
		topic.setForumId(Constants.FORUM_ID_O2S); // 运营商与运营商之间的帖子
		topic.setFromType("S"); // 服务站发帖
		topic.setToType("O"); // 运营商收贴
		topic.setFromId(companyId); // 运营商固定写0
		topic.setToId(0);
		topic.setAddTime(now); // 发表时间
		topic.setLastPostTime(now); // 最后回复时间
		topic.setReplyNumber(0); // 回复数0
		topic.setClick(0); // 点击数0
		topic.setIsTop("N"); // 不置顶

		// 添加主题
		this.dao().insert(topic);
		return true;
	}

	/**
	 * 更新主题.
	 * 
	 * @param Topic
	 * @return
	 */
	public boolean updateTopic(ForumTopic topic,int companyId) {
		this.dao().update(
				ForumTopic.class,
				Chain.make("toId",0).add("fromId",companyId)
						.add("topicTitle", topic.getTopicTitle())
						.add("topicContent", topic.getTopicContent()),
				Cnd.where("topicId", "=", topic.getTopicId()));
		return true;
	}

	/**
	 * 删除主题（逻辑删除）.
	 * 
	 * @param topicId
	 */
	public void deleteTopic(int topicId) {
		this.dao().update(ForumTopic.class, Chain.make("deleteFlag", 1),
				Cnd.where("topicId", "=", topicId));
	}

	/**
	 * 取得主题回复列表.
	 * 
	 * @param topicId
	 *            主题ID
	 * @return
	 */
	public List<ForumReply> getReplyList(int topicId) {

		// 条件
		SqlExpressionGroup group = Cnd.exps("topicId", "=", topicId);
		group = group.and("deleteFlag", "=", 0);

		// 查询
		List<ForumReply> resultList = this.dao().query(ForumReply.class,
				Cnd.where(group).asc("replyId"));
		for (ForumReply reply : resultList) {
			if (reply.getFromType().equals("O")) {
				reply.setFromName("运营商");
			} else {
				reply.setFromName(this.getSupplierName(reply.getFromId()));
			}
		}
		return resultList;
	}

	/**
	 * 保存回复.
	 * 
	 * @param reply
	 */
	public void addOrUpdateReply(ForumReply reply,int companyId) {
		if (reply.getReplyId() > 0) {
			updateReply(reply,companyId);
		}
		addReply(reply,companyId);
	}

	/**
	 * 添加回复.
	 * 
	 * @param reply
	 * @return
	 */
	public void addReply(ForumReply reply,int companyId) {

		Date now = new Date();
		reply.setFromType("S"); // 运营商
		reply.setFromId(companyId); // 运营商固定写0
		reply.setAddTime(now);
		reply.setDeleteFlag(0);
		this.dao().insert(reply);

		// 更新主题帖的回复数等信息
		ForumTopic topic = this.getTopic(reply.getTopicId());
		this.dao().update(
				ForumTopic.class,
				Chain.make("replyNumber", topic.getReplyNumber() + 1).add(
						"lastPostTime", now),
				Cnd.where("topicId", "=", reply.getTopicId()));

	}

	/**
	 * 更新回复.
	 * 
	 * @param reply
	 * @return
	 */
	public void updateReply(ForumReply reply,int companyId) {
		this.dao().update(ForumReply.class,
				Chain.make("replyContent", reply.getReplyContent()).add(
						"replyId", companyId),
				Cnd.where("replyId", "=", reply.getReplyId()));
	}

	/**
	 * 主题帖的查看次数+1.
	 */
	public void updateTopicClick(int topicId, int click) {
		this.dao().update(ForumTopic.class, Chain.make("click", click),
				Cnd.where("topicId", "=", topicId));
	}

}
